package com.yh.correct.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.yh.common.utils.ExcelUtil;
import com.yh.correct.model.Chat;
import com.yh.correct.model.Page;
import com.yh.correct.model.ResultData;
import com.yh.correct.service.IChatService;
import com.yh.correct.service.ICorrectedPersonService;



@RestController
@RequestMapping("/chat")
public class ChatController {

	private static Logger logger = LogManager.getLogger(ChatController.class);

	@Autowired
	private IChatService chatService; 
	
	@Autowired
	private ICorrectedPersonService correctedPersonService;
	
	/**
	 * 首页跳转
	 * 
	 * @return
	 */
	@RequestMapping(value="/skip")
	public ModelAndView skip(){ 
		return new ModelAndView("education/chat");
	}
	
	/**
	 * 调取别人的业务层，获取别人表中的矫正人员列表
	 * 
	 * @author 陈帅
	 */
	@RequestMapping(value = "/showCorrect")
	public List<Map<String, Object>> showCorrect() {

		List<Map<String, Object>> list = null;
		try {
			list = correctedPersonService.getAllCorrectedPerson();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(list);
		return list;
	}

	
	/**
	 * 添加个人谈话
	 * @throws Exception 
	 */
	@RequestMapping(value ="/add")
	public ResultData add(Chat c) throws Exception{	
	int i=chatService.addChat(c);
	ResultData rd=new ResultData();	
	if(i>0){
		rd.setCode(0);
	    rd.setMessage("插入成功！");
	}else{
		rd.setCode(-1);
		rd.setMessage("插入失败");
	}
		
		return rd; 
    }
	
	/**
	 * 根据id查询单个思想教育
	 * 
	 * @author 陈帅
	 * @throws Exception 
	 */
	@RequestMapping(value = "/get")
	public ModelAndView getThought(Chat c) throws Exception {
		Map<String, Object> map = chatService.getChat(c);
		logger.info("查个人谈话正登记" + map);
		return new ModelAndView("education/chat_edit", map);
	}
	/**
	 * 修改个人谈话
	 * @throws Exception 
	 */
	@RequestMapping(value ="/edit")
	public ResultData edit(Chat c) throws Exception {
		int i =chatService.editChat(c);
		ResultData rd = new ResultData();
		if (i > 0) {
			rd.setCode(0);
			rd.setMessage("修改成功！");
		} else {
			rd.setCode(-1);
			rd.setMessage("修改失败");
		}
		return rd;
	}

	/**
	 * 适用于添加表中的视图渲染
	 * 
	 * @author 陈帅
	 */
	@RequestMapping("/addView")
	public ModelAndView add() {
		return new ModelAndView("education/chat_add");
	}

	/**
	 * 删除个人谈话
	 * @throws Exception 
	 */
	@RequestMapping(value = "/del")
	public ResultData del(Chat c) throws Exception {
		logger.debug("删除矫正方案" + c);
		int i = chatService.delChat(c);
		ResultData rd = new ResultData();
		if (i > 0) {
			rd.setCode(0);
			rd.setMessage("删除成功！");
		} else {
			rd.setCode(-1);
			rd.setMessage("删除失败");
		}
		return rd;
	}
	/**
	 * 模糊查询个人谈话
	 * @throws Exception 
	 */
	@RequestMapping(value = "/getLike")
	public ResultData getLikeProjects(String name, String date,Integer pageSize,Integer pageNum) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("pdName", name);
		map.put("likedate",date);
		map.put("pageSize", pageSize);
		map.put("pageNum",pageNum);
		Page page = chatService.getLikeChats(map);
		ResultData rd = new ResultData();
		List<Object> list = new ArrayList<Object>();
		if (page != null) {
			list.add(page);
			rd.setCode(0);
			rd.setMessage("查询成功！");
			rd.setData(list);
		} else {
			rd.setCode(-1);
			rd.setMessage("查询失败！");
		}
		return rd;
	}

	/**
	 * 导出Excle
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/excel")
	public String outExcle(HttpServletRequest request, HttpServletResponse response){
		String fileName = "个人谈话登记文件";
		List<Map<String, Object>> projects = outData();
		List<Map<String, Object>> list = outExcelRecord(projects);
		String columnNames[] = { "编号", "矫正单位", "姓名", "谈话日期", "谈话人", "记录人", "谈话地点"};
		String keys[] = { "id", "jdName", "pdName", "chat_date", "chat_man", "record_man", "chat_address"};
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			ExcelUtil.createWorkBook(list, keys, columnNames).write(os);
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] content = os.toByteArray();
		InputStream is = new ByteArrayInputStream(content);
		response.reset();
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		try {
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (final IOException e) {
			try {
				throw e;
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} finally {
			if (bis != null)
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if (bos != null)
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		return null;
	}
	/**
	 * 导出Excel时获取所有信息
	 * 
	 * @return
	 */
	private List<Map<String, Object>> outData(){
		// TODO Auto-generated method stub
		List<Map<String, Object>> list = null;
		try {
			list = chatService.getAllC();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
	/**
	 * 记录要导出的所有信息
	 * 
	 * @param projects
	 * @return
	 */
	private List<Map<String, Object>> outExcelRecord(List<Map<String, Object>> projects){
		List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("sheetName", "sheet1");
		listmap.add(map);
		Map<String, Object> object = null;
		for (int j = 0; j < projects.size(); j++) {
			object = projects.get(j);
			Map<String, Object> mapValue = new HashMap<String, Object>();
			mapValue.put("id", object.get("id"));
			mapValue.put("jdName", object.get("jdName"));
			mapValue.put("pdName", object.get("pdName"));
			mapValue.put("chat_date", object.get("chat_date"));
			mapValue.put("chat_man", object.get("chat_man"));
			mapValue.put("record_man", object.get("record_man"));
			mapValue.put("chat_address", object.get("chat_address"));
			listmap.add(mapValue);
		}
		return listmap;
	}
	
}
